package com.ferris.redbook.controller;

import com.ferris.redbook.dto.response.FileUploadResponse;
import com.ferris.redbook.service.FileService;
import com.ferris.redbook.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/upload")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/image")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            FileUploadResponse response = fileService.uploadImage(file);
            return AjaxResult.success("图片上传成功", response);
        } catch (Exception e) {
            return AjaxResult.error("图片上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/avatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            FileUploadResponse response = fileService.uploadAvatar(file);
            return AjaxResult.success("头像上传成功", response);
        } catch (Exception e) {
            return AjaxResult.error("头像上传失败: " + e.getMessage());
        }
    }

    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam("filePath") String filePath) {
        try {
            boolean deleted = fileService.deleteFile(filePath);
            if (deleted) {
                return AjaxResult.success("文件删除成功");
            } else {
                return AjaxResult.error("文件删除失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("文件删除失败: " + e.getMessage());
        }
    }
}